package com.zenithsun.common.basicdata.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.syzg.common.config.SysProperties;
import com.syzg.common.controller.BaseController;
import com.syzg.common.model.WebInfo;
import com.syzg.common.util.SearchMap;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.model.WebObj;
import com.syzg.common.util.PKCreator;
import com.syzg.common.exception.BaseException;
import com.syzg.core.page.PageResult;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zenithsun.common.basicdata.model.Basicdata;
import com.zenithsun.common.basicdata.service.BasicdataService;
import com.zenithsun.common.bean.DownLoadVersion;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.common.image.ImageCut;
import com.zenithsun.common.image.StorageRule;
import com.zenithsun.common.util.qrcode.BuildeQRCode;

@Controller
@RequestMapping("/path/basicdata")
public class BasicdataController extends BaseController{
	
	static Logger log = LoggerFactory.getLogger(BasicdataController.class);
	
	@Resource
	private BasicdataService basicdataService;
	
	/**
	 * 设置查询条件
	 * @param webObj
	 * @param searchMap
	 */
	private void setSearchCondition(WebObj webObj,SearchMap searchMap){
		//1：从webObj中获取查询的参数webObj.getSearchValue().get("参数名称");
		//2：判断参数是否为空或空值
		//3：设置查询条件searchMap.eq("a.参数名称", 参数值);
		String id=webObj.getSearchValue().get("id");
		if(StringUtils.isNotBlank(id)){
			searchMap.eq("a.id", id);
		}
		String code=webObj.getSearchValue().get("code");
		if(StringUtils.isNotBlank(code)){
			searchMap.like("a.code", code);
		}
		String parentId=webObj.getSearchValue().get("parentId");
		if(StringUtils.isNotBlank(parentId)){
			searchMap.eq("a.parentId", parentId);
		}
		//增加排序条件
		//按编码进行升序
		searchMap.addOrder("a.code", SearchMap.ORDER_ASC);
	}
	
	@RequestMapping("/listbasicdata")
	public ModelAndView listbasicdata(WebObj webObj)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/common/basicdata/listbasicdata.jsp");
		SearchMap searchMap = SearchMap.forClass(Basicdata.class);
		setSearchCondition(webObj,searchMap);
		PageResult pageResult = basicdataService.findObjectsForPage(webObj.getPageNo(), SysProperties.PAGESIZE, searchMap);
        webObj.setPageResult(pageResult);
        mv.addObject("webObj",webObj);
        return mv;
	}
	
	@RequestMapping("/initbasicdata")
	public ModelAndView initbasicdata() throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/common/basicdata/addbasicdata.jsp");
		try {
			mv.addObject("basicdata", new Basicdata());
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.basicdata.setCreatePersonId(new String(loginObj.getPersonId()));
			this.basicdata.setCreator(loginObj.getPersonName());
			this.basicdata.setCreateTime(new Date());*/
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/addbasicdata")
	public @ResponseBody String addbasicdata(Basicdata basicdata) throws Exception {
		WebObj webObj = new WebObj();
		try {
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.basicdata.setCreatePersonId(new String(loginObj.getPersonId()));
			this.basicdata.setCreator(loginObj.getPersonName());
			this.basicdata.setCreateTime(new Date());*/
			basicdata.setId(PKCreator.getPk());
			basicdataService.create(basicdata);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add(e.getMessage());
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/viewbasicdata")
	public ModelAndView viewbasicdata(Basicdata basicdata,ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/common//basicdata/viewbasicdata.jsp");
		try {
			String id = basicdata.getId();
			Basicdata basicdataVO = basicdataService.findObjectById(id);
			mv.addObject("basicdata",basicdataVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/editbasicdata")
	public ModelAndView editbasicdata(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/common/basicdata/editbasicdata.jsp");
		try {
			Basicdata basicdata = basicdataService.findObjectById(id);
			mv.addObject("basicdata", basicdata);
			WebObj webObj = new WebObj();
			mv.addObject("webObj",webObj);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/modbasicdata")
	public @ResponseBody String modbasicdata(String id,Basicdata basicdataVO) throws Exception {
		WebObj webObj = new WebObj();
		try {
			Basicdata basicdata = basicdataService.findObjectById(id);
			basicdata = (Basicdata) MethodUtil.copyProperties(basicdata, basicdataVO);
			basicdataService.update(basicdata);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add(e.getMessage());
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/delbasicdata")
	public ModelAndView delbasicdata(String id,WebObj webObj) throws Exception {
		String[] ids = webObj.getSelectedRow();
		try {
			if(ids == null) { //删除单个
				if(id == null) {
					ids = new String[0];
				} else {
					ids = new String[]{String.valueOf(id)};
				}
			}
			String[] idsStr = new String[ids.length];
			int i = 0;
			for(String idVO: ids) {
				idsStr[i++] = new String(idVO);
			}
			basicdataService.delete(idsStr);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return listbasicdata(webObj);
	}
	
	/**
	 * 加载树形基础数据页面
	 * @author wanglei@enersun.com.cn
	 * @param mv
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping("/treebasicdata")
	public ModelAndView treebasicdata(ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/common/basicdata/treebasicdata.jsp");
		return mv;
	}
	
	/**
	 * 获取树形基础数据列表
	 * @author wanglei@enersun.com.cn
	 * @param mv
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping(value="/loadtreebasicdata",produces="application/json;charset=UTF-8")
	public @ResponseBody String loadtreebasicdata(String parentCode) throws Exception {
		OutMessage outMessage=new OutMessage();
		try {
			outMessage.setState(OutMessageState.Success);
			outMessage.setContent(basicdataService.getTreeNewsBasicData(parentCode));
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent(e.getMessage());
		}
		return JSON.toJSONString(outMessage, SerializerFeature.WriteNullStringAsEmpty);
	}
	
	@RequestMapping("/listversion")
	public ModelAndView listversion(HttpServletRequest request)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/common/version/listversion.jsp");
		List<Basicdata> listBasicdata = basicdataService.getBasicdataByParentCode("DownLoadVersion");
		StorageRule sr = new StorageRule(request);
		for(Basicdata b:listBasicdata){
			b.setRemark((sr.GetCurrProjectPathHttpPath()+StorageRule.appSavePath+b.getRemark()).replaceAll("\\\\", "/"));
		}
        mv.addObject("listBasicdata",listBasicdata);
        return mv;
	}
	
	@RequestMapping("/initversion")
	public ModelAndView initversion(String id)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/common/version/editversion.jsp");
		Basicdata basicdata = basicdataService.findObjectById(id);
        mv.addObject("basicdata",basicdata);
        return mv;
	}
	
	/**
	 * 获取下载的数据
	 * @author wanglei@enersun.com.cn
	 * @param type
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping(value="/downloadApp",produces="application/json;charset=UTF-8")
	public @ResponseBody String downloadApp(String type,HttpServletRequest request) throws Exception {
		OutMessage outMessage=new OutMessage();
		try {
			if(type==null){
				outMessage.setState(OutMessageState.Fail);
				outMessage.setContent("没有下载的应用类型");
			}else{
				DownLoadVersion down=basicdataService.getDownLoadVersion(type);
				StorageRule sr = new StorageRule(request);
				if(down!=null){
					down.setDownLoadUrl((sr.GetCurrProjectPathHttpPath()+StorageRule.appSavePath+down.getDownLoadUrl()).replaceAll("\\\\", "/"));

					outMessage.setState(OutMessageState.Success);
					outMessage.setContent(down);
				}else{
					outMessage.setState(OutMessageState.Fail);
					outMessage.setContent("没有找到下载的应用资源");
				}
			}
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent(e.getMessage());
		}
		return JSON.toJSONString(outMessage, SerializerFeature.WriteNullStringAsEmpty);
	}
	
	/**
	 * 获取下载的数据
	 * @author wanglei@enersun.com.cn
	 * @param type
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping(value="/uploadApp",produces="application/json;charset=UTF-8")
	public @ResponseBody String uploadApp(String baId,String version,HttpServletRequest request) throws Exception {
		OutMessage outMessage=new OutMessage();
		try {
			if(StringUtils.isBlank(baId)||StringUtils.isBlank(version)){
				outMessage.setState(OutMessageState.Fail);
				outMessage.setContent("参数有问题，请检查。");
			}else{
				outMessage=basicdataService.uploadAppFile(baId, version, request);
			}
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent(e.getMessage());
		}
		return JSON.toJSONString(outMessage, SerializerFeature.WriteNullStringAsEmpty);
	}
	
	/**
	 * 进入App下载页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/initAppDownload")
	public ModelAndView initAppDownload(HttpServletRequest request)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/news/mobile/appDownload.jsp");
		List<Basicdata> listBasicdata = basicdataService.getBasicdataByParentCode("DownLoadVersion");
		StorageRule sr = new StorageRule(request);
		for(Basicdata b:listBasicdata){
			b.setRemark((sr.GetCurrProjectPathHttpPath()+StorageRule.appSavePath+b.getRemark()).replaceAll("\\\\", "/"));
			mv.addObject(b.getCode(),b.getRemark());
		}
        return mv;
	}
	
	/**
	 * 进入App下载页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/buildQRCode",produces="application/json;charset=UTF-8")
	public @ResponseBody String buildQRCode(String website,HttpServletRequest request)throws Exception{
		OutMessage outMessage=new OutMessage();
		try {
			StorageRule sr = new StorageRule(request);
			String appQRCode=sr.getCurrProjectPath()+StorageRule.appSavePath+"appQRCode.png";
			String encoderContent = website+"/path/basicdata/initAppDownload";
			BuildeQRCode.createQRCode(encoderContent, appQRCode, null);
			outMessage.setState(OutMessageState.Success);
			outMessage.setContent("二维码生成成功，地址是："+appQRCode);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent(e.getMessage());
		}
        return JSON.toJSONString(outMessage);
	}
	
	/**
	 * 获取下载的数据
	 * @author wanglei@enersun.com.cn
	 * @param type
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping("/downloadAppByType")
	public ResponseEntity<byte[]> downloadAppByType(String type,HttpServletRequest request,HttpServletResponse response) throws Exception {
		try {
			if(type!=null){
				DownLoadVersion down=basicdataService.getDownLoadVersion(type);
				StorageRule sr = new StorageRule(request);
				if(down!=null){
					
					down.setDownLoadUrl((sr.getCurrProjectPath()+StorageRule.appSavePath+down.getDownLoadUrl()).replaceAll("\\\\", "/"));
					File downFile=new File(down.getDownLoadUrl());
					//download(downFile,response);
					String dfileName = new String(downFile.getName().getBytes("utf-8"),"iso8859-1");
					HttpHeaders headers = new HttpHeaders();
					headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
					headers.setContentDispositionFormData("attachment", dfileName);
					return new ResponseEntity(FileUtils.readFileToByteArray(downFile), headers, HttpStatus.CREATED);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(BaseException.addExceptionLog(e));
		}finally{
			//response.reset();
		}
		return null;
	}
	
	public void download(File file,HttpServletResponse response){
		try{
		    String filePath = file.getPath();  
		    String fileName = file.getName();
		    String destUrl = filePath;  
		      
		    String name=fileName.trim();  
		    // 建立链接    
		    URL url = new URL(destUrl);
		    HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();    
		    // 连接指定的资源    
		    httpUrl.connect();    
		    // 获取网络输入流    
		    BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());    
		  
		    response.setContentType("application/octet-stream");
		    response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(name,"GB2312"));    
		    OutputStream out = response.getOutputStream();    
		    byte[] buf = new byte[1024];    
		    if (destUrl != null) {    
		        BufferedInputStream br = bis;    
		        int len = 0;    
		        while ((len = br.read(buf)) > 0){    
		            out.write(buf, 0, len);    
		        }                   
		        br.close();    
		    }    
		    out.flush();    
		    out.close();   
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	@RequestMapping("/downloadApp")
	public HttpServletResponse download(HttpServletRequest request,HttpServletResponse response,String type) {
        try {
        	SearchMap sm = new SearchMap();
        	sm.addProperty("code", type);
        	List list = basicdataService.findObjects(sm);
        	Basicdata bd = (Basicdata)list.get(0); 
        	String path = ImageCut.class.getClassLoader().getResource("").getPath();
            path = path.substring(1,path.indexOf("WEB-INF")) + "zenithsun/app/"+bd.getRemark();
            // path是指欲下载的文件的路径
            File file = new File(path);
            // 取得文件名
            String filename = file.getName();
            // 以流的形式下载文
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment; filename=" 
            		+new String(bd.getRemark().getBytes("iso-8859-1"),"utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/x-download");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return response;
    }
}